package com.lisp.dl;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.lisp.dl.classloader.ModuleClassLoader;
import com.lisp.dl.module.IModule;

public class ModuleManager {

	private static Map<String, IModule> modules = new ConcurrentHashMap<String, IModule>();
	
	public static IModule get(String classSimpleName) throws Exception {
		IModule m = modules.get(classSimpleName);
		if(m != null) {
			return m;
		}

		System.out.println("initialize " + classSimpleName);
		return dynamicLoad(classSimpleName);
	}
	
	public static IModule dynamicLoad(String classSimpleName) throws Exception {
		ModuleClassLoader mcl = new ModuleClassLoader();
		String fullName = ModuleClassLoader.MODULE_IMPL_PACKAGE + classSimpleName;
		// 注意: 这里有可能产生ClassCastException
		IModule module = (IModule) mcl.loadClass(fullName).newInstance();
		modules.put(module.getClass().getSimpleName(), module);
		return module;
	}
}
